function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i
    }
  }
  return -1
}
var snbc = require("../../utils/print-sdk.js");
Page({

  data: {
    devices: [],
    connected: false,
    btnScaning:'开始扫描',
    chs: [],
    deviceIdtest:'',
    isScanning: false,
    scanTimeout: null
  },

  onLoad() {
    // 页面加载时初始化SDK
    this.initBluetooth();
  },

  onUnload() {
    this.cleanup();
  },

  // 初始化蓝牙
  initBluetooth: function() {
    console.log('🚀 初始化蓝牙...');

    const that = this;

    // 检查蓝牙权限
    snbc.SnbcPrinter.checkBluetoothPermission().then(() => {
      console.log('✅ 蓝牙权限检查通过');

      // 注册连接状态回调
      snbc.SnbcPrinter.regeisterFUN((res) => {
        console.log('🔗 连接状态变化:', res);
      });

      console.log('✅ 蓝牙初始化完成');

    }).catch((error) => {
      console.error('❌ 蓝牙初始化失败:', error);
      // wx.showModal({
      //   title: '蓝牙初始化失败',
      //   content: (error.message || '请检查蓝牙是否开启，并允许小程序使用蓝牙权限'),
      //   showCancel: false
      // });
    });
  },

  openBluetoothAdapter() {
    if(this.data.btnScaning =='开始扫描') {
      this.startScan();
    } else {
      this.stopScan();
    }
  },

  // 开始扫描
  startScan() {
    if (this.data.isScanning) {
      console.log('⚠️ 正在扫描中，忽略重复请求');
      return;
    }

    console.log('🔍 开始扫描蓝牙设备...');

    this.setData({
      isLoading: true,
      isDisabled: true,
      btnScaning: '停止扫描',
      devices: [],
      isScanning: true
    });

    wx.showLoading({title: '扫描中…'});

    // 设置扫描超时（15秒）
    this.data.scanTimeout = setTimeout(() => {
      console.log('⏰ 扫描超时，自动停止');
      this.stopScan();

      if (this.data.devices.length === 0) {
        wx.showModal({
          title: '扫描结果',
          content: '未发现任何蓝牙设备，请确保：\n1. 蓝牙设备已开启并处于可发现状态\n2. 设备距离足够近\n3. 已授权蓝牙权限',
          showCancel: false
        });
      }
    }, 15000);

    snbc.SnbcPrinter.startBleDiscovery({
      models: '', // 改为空字符串，搜索所有设备
      timeout: 15000, // 15秒超时
      interval: 0, // 设置为0，实时上报

      callback: (res) => {
        console.log('📱 发现设备:', res.devices);

        if (res.devices && res.devices.length > 0) {
          res.devices.forEach(device => {
            // 放宽设备过滤条件
            if (!device.name && !device.localName && !device.advertisData) {
              console.log('⚠️ 跳过无名称设备:', device.deviceId);
              return;
            }

            // 显示设备名称（优先使用name，其次localName，最后显示deviceId）
            const deviceName = device.name || device.localName || `未知设备(${device.deviceId.slice(-4)})`;
            device.displayName = deviceName;

            console.log('✅ 处理设备:', deviceName, device.deviceId);

            const foundDevices = this.data.devices;
            const idx = inArray(foundDevices, 'deviceId', device.deviceId);
            const data = {};

            if (idx === -1) {
              data[`devices[${foundDevices.length}]`] = device;
              console.log('➕ 添加新设备:', deviceName);
            } else {
              data[`devices[${idx}]`] = device;
              console.log('🔄 更新设备:', deviceName);
            }

            this.setData(data);
          });
        }
      },

      success: (res) => {
        console.log('✅ 扫描启动成功:', res);
      },

      fail: (error) => {
        console.error('❌ 扫描启动失败:', error);
        this.stopScan();

        wx.showModal({
          title: '扫描失败',
          content: `启动蓝牙扫描失败：${error.errMsg || '未知错误'}\n\n请检查：\n1. 蓝牙是否已开启\n2. 是否已授权蓝牙权限\n3. 定位权限是否已开启（Android需要）`,
          showCancel: false
        });
      },

      complete: (res) => {
        console.log('🔄 扫描请求完成:', res);
      }
    });
  },

  // 停止扫描
  stopScan() {
    console.log('🛑 停止扫描');

    // 清除超时定时器
    if (this.data.scanTimeout) {
      clearTimeout(this.data.scanTimeout);
      this.data.scanTimeout = null;
    }

    this.setData({
      btnScaning: '开始扫描',
      isScanning: false,
      isLoading: false,
      isDisabled: false
    });

    wx.hideLoading();

    snbc.SnbcPrinter.stopBleDiscovery({
      success: (res) => {
        console.log('✅ 停止扫描成功:', res);
      },
      fail: (error) => {
        console.error('❌ 停止扫描失败:', error);
      },
      complete: (res) => {
        console.log('🔄 停止扫描完成:', res);
      }
    });
  },

  //点击事件处理
  createBLEConnection: function (e) {
    const deviceId = e.currentTarget.dataset.deviceId;
    const name = e.currentTarget.dataset.name || e.currentTarget.dataset.displayname || '未知设备';

    console.log('🔗 选择连接设备:', name, deviceId);

    // 停止扫描
    this.stopScan();

    wx.navigateTo({
      url: '../write/write?deviceId=' + deviceId + '&name=' + encodeURIComponent(name) + '&panziqiang=happy' + '&newBoothName=' + encodeURIComponent(name) + '&isDisabled=' + false,
      success: () => {
        console.log('✅ 页面跳转成功');
      },
      fail: (error) => {
        console.error('❌ 页面跳转失败:', error);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'error'
        });
      }
    });
  },

  // 清理资源
  cleanup() {
    console.log('🧹 清理页面资源...');

    // 停止扫描
    this.stopScan();

    // 清理SDK资源
    snbc.SnbcPrinter.cleanup();
  },

  closeBluetoothAdapter() {
    this.cleanup();
  },

  // 手动刷新
  onRefresh() {
    if (!this.data.isScanning) {
      this.startScan();
    }
  },

  // 检查蓝牙状态
  checkBluetoothStatus() {
    wx.showLoading({ title: '检查中...' });

    wx.getBluetoothAdapterState({
      success: (res) => {
        wx.hideLoading();
        console.log('📡 蓝牙适配器状态:', res);

        let statusText = `蓝牙状态：\n`;
        statusText += `- 可用：${res.available ? '是' : '否'}\n`;
        statusText += `- 搜索中：${res.discovering ? '是' : '否'}\n`;

        if (!res.available) {
          statusText += `\n⚠️ 蓝牙不可用，请开启蓝牙后重试`;
        }

        wx.showModal({
          title: '蓝牙状态',
          content: statusText,
          showCancel: !res.available,
          cancelText: '取消',
          confirmText: res.available ? '知道了' : '去设置',
          success: (modalRes) => {
            if (modalRes.confirm && !res.available) {
              // 引导用户到系统设置
              wx.openSetting({
                success: (settingRes) => {
                  console.log('设置页面返回:', settingRes);
                }
              });
            }
          }
        });
      },
      fail: (error) => {
        wx.hideLoading();
        console.error('❌ 获取蓝牙状态失败:', error);
        wx.showModal({
          title: '蓝牙检查失败',
          content: `无法获取蓝牙状态：${error.errMsg}\n\n可能原因：\n1. 蓝牙权限未授权\n2. 蓝牙适配器未初始化`,
          showCancel: true,
          cancelText: '取消',
          confirmText: '去设置',
          success: (modalRes) => {
            if (modalRes.confirm) {
              wx.openSetting();
            }
          }
        });
      }
    });
  },

});
